<template>
    <div class="app-container home">
        <el-row :gutter="20">
            <el-col :sm="24" :lg="24">
                <blockquote class="text-warning" style="font-size: 14px">
                    <el-form
                        :inline="true"
                        :model="formInline"
                        class="demo-form-inline"
                    >
                        <el-form-item label="姓名">
                            <el-input
                                v-model="formInline.name"
                                placeholder="请输入姓名"
                            />
                        </el-form-item>
                        <el-form-item label="联系电话">
                            <el-input
                                v-model="formInline.tel"
                                placeholder="请输入联系电话"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button
                                type="primary"
                                @click="handleQuery"
                                :disabled="newTableData.length === 0"
                                >查询
                            </el-button>
                            <el-button
                                type="primary"
                                @click="resetQuery"
                                :disabled="newTableData.length === 0"
                                >重置</el-button
                            >
                            <el-button
                                :disabled="newTableData.length === 0"
                                type="primary"
                                plain
                                icon="Plus"
                                @click="handleAdd"
                                >新增</el-button
                            >
                        </el-form-item>
                    </el-form>
                    <div class="demo1" id="box">
                        <el-upload
                            ref="upload1"
                            class="upload-demo"
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                            :limit="1"
                            :on-exceed="handleExceed1"
                            :auto-upload="false"
                            :on-change="handleUpload1"
                        >
                            <template #trigger>
                                <el-button size="large" type="primary"
                                    >上传</el-button
                                >
                            </template>
                            <template #tip>
                                <div class="el-upload__tip text-red">
                                    limit 1 file, 回收名单
                                </div>
                            </template>
                        </el-upload>
                        <el-upload
                            ref="upload2"
                            class="upload-demo"
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                            :limit="1"
                            :on-exceed="handleExceed2"
                            :on-change="handleUpload2"
                            :auto-upload="false"
                        >
                            <template #trigger>
                                <el-button size="large" type="primary"
                                    >上传</el-button
                                >
                            </template>
                            <template #tip>
                                <div class="el-upload__tip text-red">
                                    limit 1 file, 订购名单
                                </div>
                            </template>
                        </el-upload>
                        <el-button
                            :disabled="newTableData.length === 0"
                            size="large"
                            type="primary"
                            @click="exportData"
                            >导出table中的数据
                        </el-button>
                    </div>
                </blockquote>
            </el-col>
        </el-row>

        <el-table :data="tableData" border style="width: 100%" height="450">
            <el-table-column type="index" width="60" label="序号" />
            <el-table-column prop="票号" label="票号" />
            <el-table-column prop="村队" label="村队" width="180" />
            <el-table-column prop="姓名" label="姓名" width="110" />
            <el-table-column prop="联系电话" label="联系电话" width="180" />
            <el-table-column prop="规格型号" label="规格型号" />
            <el-table-column prop="回收亩数" label="回收亩数" />
            <el-table-column prop="卷数" label="卷数" />
            <el-table-column prop="发货数量" label="发货数量" />
            <el-table-column prop="回收" label="回收" />
            <el-table-column prop="差" label="差">
                <template #default="scope">
                    <el-text class="mx-1" type="danger">
                        {{ scope.row["差"] }}
                    </el-text>
                </template>
            </el-table-column>
            <el-table-column prop="开票人员" label="开票人员" />
            <el-table-column prop="领取公斤" label="领取公斤" />
            <el-table-column prop="领取方式" label="领取方式">
                <template #default="scope">
                    <el-text
                        class="mx-1"
                        type="primary"
                        v-if="scope.row['领取方式'] == '租用'"
                    >
                        {{ scope.row["领取方式"] }}
                    </el-text>
                    <el-text
                        class="mx-1"
                        type="success"
                        v-if="scope.row['领取方式'] == '租赁'"
                    >
                        {{ scope.row["领取方式"] }}
                    </el-text>
                    <el-text
                        class="mx-1"
                        type="info"
                        v-if="scope.row['领取方式'] == '兑换'"
                    >
                        {{ scope.row["领取方式"] }}
                    </el-text>
                    <el-text
                        class="mx-1"
                        type="warning"
                        v-if="scope.row['领取方式'] == '购买'"
                    >
                        {{ scope.row["领取方式"] }}
                    </el-text>
                    <el-text
                        class="mx-1"
                        type="danger"
                        v-if="scope.row['领取方式'] == '配送'"
                    >
                        {{ scope.row["领取方式"] }}
                    </el-text>
                    <el-text
                        class="mx-1"
                        type="danger"
                        v-if="scope.row['领取方式'] == '退回'"
                    >
                        {{ scope.row["领取方式"] }}
                    </el-text>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
                    <el-button
                        link
                        type="primary"
                        @click="handleEdit(scope.row)"
                        >修改</el-button
                    >
                    <el-button
                        link
                        type="primary"
                        @click="handleDel(scope.$index, scope.row['姓名'])"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <Pagination
            :total="newTableData.length"
            :page="page"
            :limit="limit"
            @update:page="update_page"
            @update:limit="update_limit"
            @pagination="pagination"
        />
        <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" v-model="open" :align-center="true">
            <el-form
                :model="form"
                :rules="rules"
                ref="userRef"
                label-width="100px"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="票号" prop="票号">
                            <el-input
                                v-model="form['票号']"
                                placeholder="请输入票号"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="村队" prop="村队">
                            <el-input
                                v-model="form['村队']"
                                placeholder="请输入村队"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="姓名">
                            <el-input
                                v-model="form['姓名']"
                                placeholder="请输入姓名"
                                maxlength="12"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="联系电话">
                            <el-input
                                v-model="form['联系电话']"
                                placeholder="请输入联系电话"
                                maxlength="11"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="规格型号" prop="规格型号">
                            <el-input
                                v-model="form['规格型号']"
                                placeholder="请输入规格型号"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="回收亩数" prop="回收亩数">
                            <el-input
                                v-model="form['回收亩数']"
                                placeholder="请输入回收亩数"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="卷数" prop="卷数">
                            <el-input
                                v-model="form['卷数']"
                                placeholder="请输入卷数"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="发货数量" prop="发货数量">
                            <el-input
                                v-model="form['发货数量']"
                                placeholder="请输入发货数量"
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="回收" prop="回收">
                            <el-input
                                v-model="form['回收']"
                                placeholder="请输入回收"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="差" prop="差">
                            <el-input
                                v-model="form['差']"
                                placeholder="请输入差"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开票人员" prop="开票人员">
                            <el-input
                                v-model="form['开票人员']"
                                placeholder="请输入开票人员"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="领取公斤" prop="领取公斤">
                            <el-input
                                v-model="form['领取公斤']"
                                placeholder="请输入领取公斤"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="领取方式" prop="领取方式">
                            <el-select
                                v-model="form['领取方式']"
                                placeholder="请选择领取方式"
                            >
                                <el-option
                                    label="兑换"
                                    value="兑换"
                                ></el-option>
                                <el-option
                                    label="租用"
                                    value="租用"
                                ></el-option>
                                <el-option
                                    label="退回"
                                    value="退回"
                                ></el-option>
                                <el-option
                                    label="购买"
                                    value="购买"
                                ></el-option>
                                <el-option
                                    label="配送"
                                    value="配送"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Function1">
import { ref, reactive } from "vue";
import { genFileId } from "element-plus";
import * as XLSX from "xlsx";
import { exportExcel } from "../exportExcel";
const { proxy } = getCurrentInstance();
const open = ref(false);
const title = ref("");
const editTableName = ref(null);
const data = reactive({
    form: {},
    rules: {
        ["票号"]: [
            {
                required: true,
                message: "请输入票号",
                trigger: "blur",
            },
        ],
        ["村队"]: [
            {
                required: true,
                message: "请输入村队",
                trigger: "blur",
            },
        ],
        ["姓名"]: [
            { required: true, message: "姓名不能为空", trigger: "blur" },
            {
                min: 2,
                max: 20,
                message: "姓名长度必须介于 2 和 20 之间",
                trigger: "blur",
            },
        ],
        ["联系电话"]: [
            {
                required: true,
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                message: "请输入正确的联系电话",
                trigger: "blur",
            },
        ],
        ["规格型号"]: [
            {
                required: true,
                message: "请输入规格型号",
                trigger: "blur",
            },
        ],
        ["回收亩数"]: [
            {
                required: true,
                message: "请输入回收亩数",
                trigger: "blur",
            },
        ],
        ["卷数"]: [
            {
                required: true,
                message: "请输入卷数",
                trigger: "blur",
            },
        ],
        ["发货数量"]: [
            {
                required: true,
                message: "请输入发货数量",
                trigger: "blur",
            },
        ],
        ["回收"]: [
            {
                required: true,
                message: "请输入回收",
                trigger: "blur",
            },
        ],
        ["差"]: [
            {
                required: true,
                message: "请输入差",
                trigger: "blur",
            },
        ],
        ["开票人员"]: [
            {
                required: true,
                message: "请输入开票人员",
                trigger: "blur",
            },
        ],
        ["领取公斤"]: [
            {
                required: true,
                message: "请输入领取公斤",
                trigger: "blur",
            },
        ],
        ["领取方式"]: [
            {
                required: true,
                message: "请输入领取方式",
                trigger: "blur",
            },
        ],
    },
});
const { form, rules } = toRefs(data);
const upload1 = ref();
const upload2 = ref();
let dgList = ref([]);
const tableData = ref([]);
const newTableData = ref([]);
const page = ref(1);
const limit = ref(10);
const formInline = reactive({
    name: "",
    tel: "",
});
const handleQuery = () => {
    page.value = 1;
    let { name, tel } = formInline;
    if (name || tel) {
        tableData.value = newTableData.value.filter((item) => {
            return (
                (!name || item["姓名"] == name) &&
                (!tel || item["联系电话"] == tel)
            );
        });
        if (tableData.value.length === 0) {
            proxy.$modal.msgError("抱歉没找到！");
        } else {
            proxy.$modal.msgSuccess("查询成功");
        }
    }
};
const resetQuery = () => {
    formInline.name = "";
    formInline.tel = "";
    tableData.value = newTableData.value.slice(0, 10);
    page.value = 1;
};
/** 取消按钮 */
function cancel() {
    open.value = false;
}
/** 新增按钮操作 */
function handleAdd() {
    form.value = {};
    title.value = "添加用户";
    open.value = true;
}
/** 修改按钮操作 */
function handleEdit(item) {
    form.value = item;
    editTableName.value = item["姓名"];
    open.value = true;
    title.value = "修改用户";
}
/** dialog确定按钮 */
function submitForm() {
    proxy.$refs["userRef"].validate((valid) => {
        if (valid) {
            if (title.value == "修改用户") {
                let index = tableData.value.findIndex(
                    (obj) => obj["姓名"] === editTableName.value
                );
                tableData.value[index] = form.value;
                let newTableIndex = newTableData.value.findIndex(
                    (obj) => obj["姓名"] === editTableName.value
                );
                newTableData.value[newTableIndex] = form.value;
                proxy.$modal.msgSuccess("修改成功");
                open.value = false;
            } else {
                newTableData.value.push(form.value);
                proxy.$modal.msgSuccess("新增成功");
                open.value = false;
            }
        }
    });
}
const handleDel = (index, name) => {
    proxy.$modal
        .confirm('是否确认删除用户姓名为"' + name + '"的数据项？')
        .then(() => {
            tableData.value.splice(index, 1);
            let newTableIndex = newTableData.value.findIndex(
                (obj) => obj["姓名"] === name
            );
            newTableData.value.splice(newTableIndex, 1);
            proxy.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
};
const update_page = (payload) => {
    page.value = payload;
};
const update_limit = (payload) => {
    limit.value = payload;
};
const pagination = (payload) => {
    let { limit, page } = payload;
    const start = (page - 1) * limit;
    const end = start + limit;
    tableData.value = newTableData.value.slice(start, end);
};
const uniq = (arr1, arr2, key) => {
    let ids = arr2.map((item) => item[key]);
    return arr1.filter((el) => {
        return !ids.includes(el[key]);
    });
};
let arrFun = (dataList, text) => {
    return dataList.reduce((total, cur, index) => {
        let hasValue = total.findIndex((current) => {
            return current["姓名"] === cur["姓名"];
        });
        hasValue === -1 && total.push(cur);
        hasValue !== -1 &&
            (total[hasValue][text] = total[hasValue][text] + cur[text]);
        return total;
    }, []);
};
function groupByTwoKeys(array, key1, key2) {
    return array.reduce((result, currentItem) => {
        const groupKey1 = currentItem[key1];
        const groupKey2 = currentItem[key2];
        let group = result.find(
            (group) => group.key1 === groupKey1 && group.key2 === groupKey2
        );
        if (!group) {
            group = { key1: groupKey1, key2: groupKey2, items: [] };
            result.push(group);
        }
        group.items.push(currentItem);
        return result;
    }, []);
}
// 每次只能上传一个
const handleExceed1 = (files) => {
    upload1.value.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    upload1.value.handleStart(file);
};
// 每次只能上传一个
const handleExceed2 = (files) => {
    upload2.value.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    upload2.value.handleStart(file);
};
// 每次上传的逻辑
const handleUpload1 = (file, fileList) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        const sheet_name_list = workbook.SheetNames;
        const first_sheet_name = sheet_name_list[0];
        const worksheet = workbook.Sheets[first_sheet_name];
        const json_data = XLSX.utils.sheet_to_json(worksheet);
        // 处理json数据
        let arr2 = [];
        let arr3 = [];
        json_data.forEach((item) => {
            if (item.type === 2) {
                arr2.push(item);
            } else if (item.type === 3) {
                arr3.push(item);
            }
        });

        // 开始算3
        arr3.map((item, index) => {
            if (!item["净重"]) {
                item["净重"] = arr3[index - 1]["净重"];
            }
            item["亩数"] = item["亩数"] * 12;
        });
        const groupedItems = groupByTwoKeys(arr3, "净重", "票号");
        groupedItems.map((item) => {
            let num1 = 0;
            item.items.map((v) => {
                num1 = v["亩数"] + num1;
            });
            item.items.map((o) => {
                o.num2 = Math.round((o["净重"] - num1) / item.items.length);
            });
            item.items.map((m) => {
                m["净重"] = Math.round(m["亩数"] + m.num2);
            });
        });

        let newArr3 = [];
        groupedItems.map((item) => {
            item.items.map((v) => {
                newArr3.push(v);
            });
        });
        let newArr = arrFun(newArr3, "净重").concat(arrFun(arr2, "净重"));
        dgList.value = arrFun(newArr, "净重");
    };
    reader.readAsArrayBuffer(file.raw);
};
// 每次上传的逻辑
const handleUpload2 = (file, fileList) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: "array" });
        const sheet_name_list = workbook.SheetNames;
        const first_sheet_name = sheet_name_list[0];
        const worksheet = workbook.Sheets[first_sheet_name];
        const json_data = XLSX.utils.sheet_to_json(worksheet);
        json_data.map((item, index) => {
            item["发货数量"] = Math.round(item["发货数量"]) || 0;
            if (item["type"] == "2") {
                item["姓名"] = json_data[index - 1]["姓名"];
            }
        });
        let dataList = arrFun(json_data, "发货数量");
        dataList.map((item) => {
            item["回收"] = 0;
            dgList.value.map((v) => {
                if (item["姓名"] == v["姓名"]) {
                    item["回收"] = Math.round(v["净重"]);
                }
            });
        });
        dataList.map((item) => {
            item["差"] = item["发货数量"] - item["回收"];
        });
        let gbs = uniq(dgList.value, dataList, "姓名");
        gbs.map((item) => {
            item["姓名"] = item["姓名"];
            item["回收"] = item["净重"];
        });
        newTableData.value = arrFun(dataList.concat(gbs), "回收");
        if (newTableData.value.length === 0) {
            proxy.$modal.msgError("上传失败，请联系技术人员");
        } else {
            tableData.value = newTableData.value.slice(0, 10);
            proxy.$modal.msgSuccess("上传成功");
        }
    };
    reader.readAsArrayBuffer(file.raw);
};
const exportData = () => {
    // 定义表头
    const headers = [
        "票号",
        "村队",
        "姓名",
        "联系电话",
        "规格型号",
        "回收亩数",
        "卷数",
        "发货数量",
        "回收",
        "差",
        "开票人员",
        "领取公斤",
        "领取方式",
    ];
    // 定义数据
    const data = [];
    newTableData.value.forEach((item) => {
        data.push([
            item["票号"],
            item["村队"],
            item["姓名"],
            item["联系电话"],
            item["规格型号"],
            item["回收亩数"],
            item["卷数"],
            item["发货数量"],
            item["回收"],
            item["差"],
            item["开票人员"],
            item["领取公斤"],
            item["领取方式"],
        ]);
    });
    // 调用公共方法导出 Excel，开启自动列宽
    exportExcel(headers, data, "user_data.xlsx", true);
    proxy.$modal.msgSuccess("导出成功");
};
</script>

<style scoped lang="scss">
.home {
    height: 100%;
    blockquote {
        padding: 10px;
        margin: 10px 0;
        font-size: 17.5px;
        border-left: 5px solid #eee;
    }
    #box {
        display: flex;
        align-items: center;
        color: white;
        font-family: "Raleway";
        font-size: 2.5rem;
    }
    .demo1 {
        --borderWidth: 3px;
        background: #d7e7ef;
        position: relative;
        border-radius: var(--borderWidth);
        .upload-demo,
        .el-button {
            margin: 0 20px;
        }
    }
    .demo1:after {
        content: "";
        position: absolute;
        top: calc(-1 * var(--borderWidth));
        left: calc(-1 * var(--borderWidth));
        height: calc(100% + var(--borderWidth) * 2);
        width: calc(100% + var(--borderWidth) * 2);
        background: linear-gradient(
            60deg,
            #f79533,
            #f37055,
            #ef4e7b,
            #a166ab,
            #5073b8,
            #1098ad,
            #07b39b,
            #6fba82
        );
        border-radius: calc(2 * var(--borderWidth));
        z-index: -1;
        animation: animatedgradient 3s ease alternate infinite;
        background-size: 300% 300%;
    }

    @keyframes animatedgradient {
        0% {
            background-position: 0% 50%;
        }
        50% {
            background-position: 100% 50%;
        }
        100% {
            background-position: 0% 50%;
        }
    }
}
</style>
